new Vue({
    el: '#app',
    data() {
        return {
            loading: false,
            row: {},
            articleName: '',
            enterpriseName: '',
            id: this.getQueryParam('serial') || '',
            logs: [],
            canReview: false,
            stagedPayments: [],
            unitName: '',
            tradingNames: [],
            paymentNames: [],
            shipmentNames: [],
            transportNames: []
        }
    },
    mounted() {
        // 仅当传入 canReview=1 或 mode=review 时显示通过/拒绝按钮
        try {
            const cr = this.getQueryParam('canReview');
            const mode = this.getQueryParam('mode');
            this.canReview = (cr === '1') || (mode === 'review');
        } catch (e) { this.canReview = false; }
        this.init();
    },
    methods: {
        getQueryParam(key) {
            const params = window.location.search.replace(/^\?/, '').split('&').reduce((acc, cur) => {
                const [k, v] = cur.split('='); acc[decodeURIComponent(k || '')] = decodeURIComponent(v || ''); return acc;
            }, {});
            return params[key];
        },
        reload() { this.init(); },
        init() {
            if (!this.id) return;
            this.loading = true;
            // 查询主记录
            httpRequest({
                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                data: { Data: 'acquisition_unitprice', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}'` }
            }).then(res => {
                if (!res || res.length === 0) return;
                this.row = res[0];
                // 平台身份在待审核状态下自动展示审核按钮
                try {
                    const isAdmin = getCookie('enterprise') === '1';
                    if (isAdmin && String(this.row.Row_Status) === '9') {
                        this.canReview = true;
                    }
                } catch (e) {}
                // 查询商品名称
                return httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'article_info', Condition: `Article_SerialNumber='${this.row.Article_SerialNumber}'` }
                }).then(list => {
                    this.articleName = (list && list[0] && list[0].Article_Name) || '';
                }).then(() => {
                    // 查询企业名称
                    if (!this.row.Enterprise_Info_SerialNumber) return;
                    return httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: { Data: 'enterprise_info', Condition: `Enterprise_Info_SerialNumber='${this.row.Enterprise_Info_SerialNumber}'` }
                    }).then(list => {
                        this.enterpriseName = (list && list[0] && list[0].Enterprise_Name) || '';
                    })
                }).then(() => {
                    // 查询单位名称
                    if (!this.row.Article_Unit_SerialNumber) return;
                    return httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: { Data: 'article_unit', Condition: `Article_Unit_SerialNumber='${this.row.Article_Unit_SerialNumber}'` }
                    }).then(list => {
                        this.unitName = (list && list[0] && list[0].Article_Unit) || '';
                    }).catch(()=>{ this.unitName = ''; })
                })
            }).then(() => {
                // 查询分阶段付款方案
                return httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'acquisition_unitprice_staged_payment', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}'` }
                }).then(list => {
                    const order = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                    this.stagedPayments = Array.isArray(list) ? list.sort((a,b)=>{
                        const ia = order[String(a.Stage_Name||'').trim()] || 99;
                        const ib = order[String(b.Stage_Name||'').trim()] || 99;
                        if (ia === ib) {
                            const ta = new Date(a.Create_Datetime || 0).getTime();
                            const tb = new Date(b.Create_Datetime || 0).getTime();
                            return ta - tb;
                        }
                        return ia - ib;
                    }) : [];
                }).catch(()=>{ this.stagedPayments = []; })
            }).then(() => {
                // 查询交易方式映射
                const p1 = httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'acquisition_unitprice_mapping_trading', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}' AND Row_Status='0'` }
                }).then(list => {
                    const ids = Array.isArray(list) ? list.map(x => String(x.Trading_SerialNumber)) : [];
                    if (!ids.length) { this.tradingNames = []; return; }
                    return $.getJSON('../../../admin/data/trading.json').then(json => {
                        const map = {}; (json||[]).forEach(it => { map[String(it.Trading_SerialNumber)] = it.Trading_Name; });
                        this.tradingNames = ids.map(id => map[id]).filter(Boolean);
                    }).catch(()=>{ this.tradingNames = []; })
                }).catch(()=>{ this.tradingNames = []; });

                const p2 = httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'acquisition_unitprice_mapping_payment', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}' AND Row_Status='0'` }
                }).then(list => {
                    const ids = Array.isArray(list) ? list.map(x => String(x.Payment_Method_SerialNumber)) : [];
                    if (!ids.length) { this.paymentNames = []; return; }
                    return httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: { Data: 'payment_method', Condition: `Row_Status='0'` }
                    }).then(all => {
                        const map = {}; (all||[]).forEach(it => { map[String(it.Payment_Method_SerialNumber)] = it.Payment_Method; });
                        this.paymentNames = ids.map(id => map[id]).filter(Boolean);
                    }).catch(()=>{ this.paymentNames = []; })
                }).catch(()=>{ this.paymentNames = []; });

                const p3 = httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'acquisition_unitprice_mapping_shipment', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}' AND Row_Status='0'` }
                }).then(list => {
                    const ids = Array.isArray(list) ? list.map(x => String(x.Shipment_Method_SerialNumber)) : [];
                    if (!ids.length) { this.shipmentNames = []; return; }
                    return httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: { Data: 'shipment_method', Condition: `Row_Status='0'` }
                    }).then(all => {
                        const map = {}; (all||[]).forEach(it => { map[String(it.Shipment_Method_SerialNumber)] = it.Shipment_Method; });
                        this.shipmentNames = ids.map(id => map[id]).filter(Boolean);
                    }).catch(()=>{ this.shipmentNames = []; })
                }).catch(()=>{ this.shipmentNames = []; });

                const p4 = httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'acquisition_unitprice_mapping_transport', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}' AND Row_Status='0'` }
                }).then(list => {
                    const ids = Array.isArray(list) ? list.map(x => String(x.Transport_Method_SerialNumber)) : [];
                    if (!ids.length) { this.transportNames = []; return; }
                    return httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: { Data: 'transport_method', Condition: `Row_Status='0'` }
                    }).then(all => {
                        const map = {}; (all||[]).forEach(it => { map[String(it.Transport_Method_SerialNumber)] = it.Transport_Method; });
                        this.transportNames = ids.map(id => map[id]).filter(Boolean);
                    }).catch(()=>{ this.transportNames = []; })
                }).catch(()=>{ this.transportNames = []; });

                return Promise.all([p1, p2, p3, p4]);
            }).then(() => {
                // 查询拒绝记录
                return httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: 'acquisition_unitprice_examine_log', Condition: `Acquisition_Unit_Price_SerialNumber='${this.id}'` }
                }).then(list => {
                    this.logs = Array.isArray(list) ? list.sort((a,b)=>{
                        const ta = new Date(a.Operation_Datetime || a.Create_Datetime || 0).getTime();
                        const tb = new Date(b.Operation_Datetime || b.Create_Datetime || 0).getTime();
                        return tb - ta;
                    }) : [];
                }).catch(()=>{ this.logs = []; })
            }).finally(() => { this.loading = false; })
        },
        approve() {
            if (!this.row.Acquisition_Unit_Price_SerialNumber) return;
            this.$confirm('确定通过该收购审核吗？', '提示', { type: 'warning' }).then(() => {
                const mod = Object.assign({}, this.row, { Row_Status: '0' });
                const lJSONObject_Modify = { acquisition_unitprice: [mod] };
                const lJSONObject_DataSet = { Modify: lJSONObject_Modify, Add: {} };
                const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0', Operation_Path: getRelativePath(),
                    Operation_Description: '收购审核通过', Operation_Main,
                    Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                }];
                httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) })
                    .then(res => {
                        if (res.Status === 'success') {
                            this.$message.success('已通过');
                            window.location.href = './index.html';
                        } else { this.$message.error('操作失败，请重试'); }
                    })
                    .catch(() => this.$message.error('系统错误，请联系开发者!'))
            }).catch(() => { })
        },
        reject() {
            if (!this.row.Acquisition_Unit_Price_SerialNumber) return;
            this.$prompt('请输入拒绝原因', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /.+/,
                inputErrorMessage: '请输入拒绝原因',
                type: 'warning'
            }).then(({ value }) => {
                const mod = Object.assign({}, this.row, { Row_Status: '2' });
                const lJSONObject_Modify = { acquisition_unitprice: [mod] };
                const lJSONObject_DataSet = {
                    Modify: lJSONObject_Modify,
                    Add: {
                        acquisition_unitprice_examine_log: [{
                            Acquisition_Unit_Price_Examine_SerialNumber: this.id,
                            Acquisition_Unit_Price_SerialNumber: this.row.Acquisition_Unit_Price_SerialNumber || '',
                            Reason: value,
                            Creater_SerialNumber: getCookie('user') || '',
                            Create_Datetime: new Date().toISOString(),
                            Operation_ID: getCookie('user') || '',
                            Operation_Datetime: new Date().toISOString()
                        }]
                    }
                };
                const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0', Operation_Path: getRelativePath(),
                    Operation_Description: `收购审核不通过，原因：${value}`,
                    Operation_Main,
                    Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                }];
                httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) })
                    .then(res => {
                        if (res.Status === 'success') {
                            this.$message.success('已拒绝');
                            window.location.href = './index.html';
                        }
                        else { this.$message.error('操作失败，请重试'); }
                    })
                    .catch(() => this.$message.error('系统错误，请联系开发者!'))
            }).catch(() => { })
        }
    }
})